<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>{{ i18n('kernel.message.from') }}</div>
        </div>

        <div class="admin_main_block_right">
          <div>
            <el-button icon="Back" @click="router.go(-1)">
              {{ i18n('common.return') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="admin_form_main">
        <el-form label-width="120px" ref="formRef" :model="dataForm" :rules="dataRule">
          <el-form-item :label="i18n('kernel.message.type')" prop="type">
            <el-select class="width100" v-model="dataForm.type" value-key="key" @change="typeChange" placeholder>
              <el-option :key="key" :label="item.text" :value="item.value" v-for="(item, key) in typeList"/>
            </el-select>
          </el-form-item>

          <el-form-item :label="i18n('kernel.message.accept_role')" prop="role_list">
            <el-select class="width100" @change="roleSelect" :disabled="disabledAcceptType" collapse-tags multiple placeholder v-model="dataForm.role_list">
              <el-option :key="item.id" :label="item.title" :value="item.id" v-for="item in allRoleList"/>
            </el-select>
          </el-form-item>

          <el-form-item :label="i18n('kernel.message.title')" prop="title">
            <el-input type="textarea" :rows="2" :placeholder="i18n('common.please_input') + i18n('kernel.message.title')" v-model="dataForm.title" clearable></el-input>
          </el-form-item>

          <el-form-item prop="content" :label="i18n('kernel.message.content')">
            <el-input type="textarea" :rows="5" :placeholder="i18n('common.please_input') + i18n('kernel.message.content')" v-model="dataForm.content" clearable></el-input>
          </el-form-item>

          <el-form-item :label="i18n('kernel.message.author')" prop="author">
            <el-input :maxlength="10" v-model="dataForm.author" clearable/>
          </el-form-item>

          <el-form-item>
            <el-button v-if="isAuth('kernel:message:handle')" type="primary" @click="dataFormSubmit(formRef)">
              {{ i18n('common.confirm') }}
            </el-button>
            <el-button @click="resetForm(formRef)">
              {{ i18n('common.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>



<script setup name="user-form">
  import { useBase } from "@/hooks/base/useBase"
  import { useForm } from "@/hooks/form/useForm"
  import { useStore } from "@/hooks/store/useStore"

  const { user } = useStore()
  const { router, query, i18n, isAuth } = useBase()

  const model = ref('message')
  const rolelist = ref([])

  const disabledAcceptType = ref(false)
  const allRoleList = reactive([])
  const oldChooseUserList = reactive([[]])
  const oldChooseRoleList = reactive([[]])
  const typeList = ref([])

  const dataForm = reactive({
    id: 0,
    title: '',
    type: '',
    accept_type: 'user',
    role_list: [],
    content: '',
    author: '',
  })

  const dataRule = reactive({
    type: [{
      required: true,
      message: i18n('kernel.message.rules.type.require'),
      trigger: 'blur',
    }],
    title: [{
      required: true,
      message: i18n('kernel.message.rules.title.require'),
      trigger: 'blur',
    }, {
      min: 1,
      max: 100,
      message: i18n('kernel.message.rules.title.length'),
      trigger: 'blur',
    }],
    content: [{
      required: true,
      message: i18n('kernel.message.rules.content.require'),
      trigger: 'blur'
    }, {
      min: 1,
      max: 1000,
      message: i18n('kernel.message.rules.content.require'),
      trigger: 'blur'
    }]
  })

  const {
    formRef,
    dataFormSubmit,
    resetForm
  } = useForm(model.value, dataForm)

  const init = (form) => {
    dataForm.id = query.id || 0

    nextTick(() => {
      form.value.resetFields()
      if (dataForm.id) {
        $http({
          url: $http.adornUrl(`/message/view/${dataForm.id}`),
          method: 'get',
          params: $http.adornParams({}),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            dataForm.title = data.data.title
            dataForm.type = data.data.type.value + ''
            dataForm.accept_role = data.data.accept_role
            dataForm.content = data.data.content
            dataForm.author = data.data.author
            disabledAcceptType.value = true
          }
        })
      }
    })
  }

  const loadRoleList =() => {
    $http({
      url: $http.adornUrl('/role/select'),
      method: 'get',
    }).then(({ data }) => {
      if (data && data.status === 200) {
        allRoleList.push(...[{ id: '-1', title: '全选' }], ...data.data)
      } else {
        $message.error(data.message)
      }
    })
  }

  const typeChange = (select) => {
    if (select === '3') {
      disabledAcceptType.value = true
    } else {
      disabledAcceptType.value = false
    }
  }

  const loadMessageTypeList = () => {
    $http({
      url: $http.adornUrl('/dictionary/data'),
      method: 'get',
      params: $http.adornParams({
        title: 'message_type',
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        typeList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const roleSelect = (val) => {
    //保留所有值
    let allValues = allRoleList.map((item) => item.id)

    // 用来储存上一次的值，可以进行对比
    const oldVal =
      oldChooseRoleList.length === 1 ? [] : oldChooseRoleList[1]

    // 若是全部选择
    if (val.includes('-1')) {
      dataForm.role_list = allValues
    }

    // 取消全部选中  上次有 当前没有 表示取消全选
    if (oldVal.includes('-1') && !val.includes('-1')) {
      dataForm.role_list = []
    }

    // 点击非全部选中  需要排除全部选中 以及 当前点击的选项
    // 新老数据都有全部选中
    if (oldVal.includes('-1') && val.includes('-1')) {
      const index = val.indexOf('-1')
      val.splice(index, 1) // 排除全选选项
      dataForm.role_list = val
    }

    //全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
    if (!oldVal.includes('-1') && !val.includes('-1')) {
      if (val.length === allValues.length - 1) {
        dataForm.role_list = ['-1'].concat(val)
      }
    }

    //储存当前最后的结果 作为下次的老数据
    oldChooseRoleList[1] = dataForm.role_list
  }

  onMounted(() => {
    init(formRef)
    loadRoleList()
    loadMessageTypeList()
  })
</script>
